package zack.project.domain.strategy.service.rule.chain.impl;

import zack.project.domain.strategy.adapter.repository.IStrategyRepository;
import zack.project.domain.strategy.service.rule.chain.AbstractLogicChain;
import zack.project.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import zack.project.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author A1793
 */
@Slf4j
@Component("rule_blacklist")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

public class RuleBlackListLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository repository;

    @Override
    protected String ruleModels() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-黑名单开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModels());
        //根据抽奖策略id和ruleModels()【返回"rule_black_list"】查找数据库表{strategy_rule}获取对应策略规则的rule_value（黑名单规则配置）
        String ruleValue =  repository.queryStrategyRuleValue(strategyId,ruleModels());

        //数据库表:{strategy_rule}中配置:rule_model:{rule_blacklist},rule_value:{奖品id：userId}
        String[] split = ruleValue.split(Constants.COLON);

        Integer awardId = Integer.parseInt(split[0]);
        //黑名单的userId
        String[] ids = split[1].split(Constants.SPLIT);
        //循环比较本次userId是否在黑名单内
        for(String id : ids) {
            if(userId.equals(id)) {
                log.info("抽奖责任链-黑名单接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModels(), awardId);
                DefaultChainFactory.StrategyAwardVO strategyAwardVO =
                        new DefaultChainFactory.StrategyAwardVO();
                strategyAwardVO.setAwardId(awardId);
                strategyAwardVO.setLogicModel(ruleModels());
                strategyAwardVO.setAwardRuleValue("1");
                return strategyAwardVO;
            }
        }
        log.info("抽奖责任链-黑名单放行 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModels());
        //本用户不在黑名单,走下一个rule_model
        return next().logic(userId, strategyId);

    }


}

